import { serialize, noEmptyOfObject } from "@/util/util";
import store from "@/store"; // progress bar style
import { decryption } from "@/util/util";
import {deCodeKey} from "@/const/const"
axios.defaults.timeout = 30000;
// 返回其他状态吗
axios.defaults.validateStatus = function(status) {
    return status >= 200 && status <= 500; // 默认的
};
// 跨域请求，允许保存cookie
axios.defaults.withCredentials = true;

// HTTPrequest拦截
axios.interceptors.request.use(
    config => {
        const isToken = (config.headers || {}).isToken === false;
        let token = store.getters.access_token
        // 开发环境直接修改其token和jvs-rule-ua的值
        if (token && !isToken) {
          config.headers["Authorization"] = 'Bearer ' + token;
        }
        // 添加请求头 固定参数
        config.headers["jvs-rule-ua"] = encodeURI('2.1.7')
        // headers中配置serialize为true开启序列化
        if (config.methods === "post" && config.headers.serialize) {
            config.data = serialize(config.data);
            delete config.data.serialize;
        }
        // 去除空值参数
        if (config.params) {
            config.params = noEmptyOfObject(config.params)
        }
        if (config.data && config.headers['type'] != 'FormData') {
            config.data = noEmptyOfObject(config.data)
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

// HTTPresponse拦截
axios.interceptors.response.use(
    res => {
        const status = Number(res.status) || 200;
        if(status == 200 && res.data.code == 0) {
            if(res.config && res.config.url && res.config.url.startsWith('/mgr') && typeof res.data.data == 'string') {
                let tp = {
                    data: res.data.data
                }
                let temp = decryption({
                    data: tp,
                    key: deCodeKey,
                    param: ["data"]
                });
                res.data.data = JSON.parse(temp.data)
            }
            return res;
        }else{
            return Promise.reject(new Error(res));
        }
        
    },
    error => {
        if(axios.isCancel(error)) {
            return new Promise( () => {})
        }
        return Promise.reject(new Error(error));
    }
);

export default axios;
